<template>
  <div>
    <!-- 面包屑导航 -->

    <el-breadcrumb separator="/" style="margin-top:1%;">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>
        <a href="/">商品管理</a>
      </el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 主要视图 -->
    <el-card class="marginTop">
      <el-alert title="添加商品" type="info" center show-icon closable="false"></el-alert>
      <!-- 步骤条 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        class="marginTop"
        align-center="true"
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab栏 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRefs"
        label-width="100px"
        class="demo-ruleForm"
        label-position="top"
      >
        <el-tabs
          :tab-position="'left'"
          style="margin-top:1%;"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
            <!-- 名称 -->
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <!-- 价格 -->
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <!-- 重量 -->
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <!-- 数量 -->
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <!-- 分类 -->
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="catelist"
                expand-trigger="hover"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item :label="item.attr_name" v-for="item in manyTabData" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item :label="item.attr_name" v-for="item in onlyTabData" :key="item.attr_id">
              <el-input v-model="item.attr_vals" disabled></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <!-- action 图片要上传到的后天api地址 -->
            <!-- 只调动 了接口没有使用axios 所以要单独添加token-->
            <el-upload
              class="upload-demo"
              :action="uploadUrl"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :headers="headObj"
              list-type="picture"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑器 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!--添加按钮 -->
            <el-button type="primary" style="margin-top:1%;" @click="add">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="PriviewVisible" width="50%" >
      
      <img :src="previewPath" style="width:100%;">
    </el-dialog>
  </div>
</template>

<script>
import _ from 'lodash'
export default {
  data() {
    return {
      // 步骤条选中下标值
      activeIndex: "0",
      // 分类数据列表
      catelist: [],
      // 添加表单数据
      addForm: {
        // 商品名称
        goods_name: "",
        // 商品价格
        goods_price: "",
        // 商品重量
        goods_weight: "",
        // 商品数量
        goods_number: "",
        // 商品所属的分类数组
        goods_cat: [],
        // 图片列表
        pcis: [],
        // 商品详情
        goods_introduce:'',
        attrs:[]
      },
      // 用来存放图片url
      previewPath: "",
      // 图片预览
      PriviewVisible:false,
      uploadUrl: "http://timemeetyou.com:8889/api/private/v1/upload",
      // 静态属性列表
      onlyTabData: [],
      // 动态参数列表
      manyTabData: [],
      // 上传图片时添加token
      headObj: {
        Authorization: window.sessionStorage.getItem("token")
      },
      // 表单验证规则
      addFormRules: {
        goods_name: [
          {
            required: "true",
            message: "请输入商品名称",
            trigger: "blur"
          }
        ],
        goods_price: [
          {
            required: "true",
            message: "请输入商品价格",
            trigger: "blur"
          }
        ],
        goods_weight: [
          {
            required: "true",
            message: "请输入商品重量",
            trigger: "blur"
          }
        ],
        goods_number: [
          {
            required: "true",
            message: "请输入商品数量",
            trigger: "blur"
          }
        ],
        goods_cat: [
          {
            required: "true",
            message: "请选择分类",
            trigger: blur
          }
        ]
      },
      // 属性绑定
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children"
      }
    };
  },
  methods: {
    // 获取商品分类数据
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      // 判断请求是否成功
      if (res.meta.status !== 200) {
        return this.$message.error("获取分类数据失败");
      }
      // 请求成功
      this.catelist = res.data;
      // console.log(this.catelist);
    },
    // 级联选择器数据发生变化时
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    // tabs里面的发生变化时,activeName将要调到的模块，oldActiveName原来的模块
    beforeTabLeave(activeName, oldActiveName) {
      // 判断如果是首页或者是分类未选择
      if (oldActiveName === "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类！");
        return false;
      }
    },
    // 获取动态参数
    async tabClicked() {
      // 动态参数
      if (this.activeIndex === "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "many" }
          }
        );
        if (res.meta.status !== 200) {
          return this.$message.error("获取动态参数失败！");
        }

        res.data.forEach(item => {
          item.attr_vals =
            item.attr_vals.length === 0 ? [] : item.attr_vals.split(" ");
        });
        this.manyTabData = res.data;
      } else if (this.activeIndex === "2") {
        // 商品属性
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: "only" }
          }
        );
        // 判断获取数据是否成功
        if (res.meta.status !== 200) {
          return this.$message.error("获取静态属性失败");
        }

        this.onlyTabData = res.data;
        console.log(this.onlyTabData);
      }
    },
    // 预览时调用
    handlePreview(file) {
      this.previewPath = file.response.data.url;
      this.PriviewVisible = true
    },
    // 删除图片时调用
    handleRemove(file) {
      // 找到文件
      const filePath = file.response.data.tem_path;
      // 在pics这个数组中寻找file
      const i = this.addForm.pcis.findIndex(x => x.pic === filePath);
      // 删除pics里面的
      this.addForm.pics.splice(i, 1);
      console.log(this.addForm);
    },
    // 图片上传成功时的方法
    handleSuccess(response) {
      // 现获取图片路径
      // 再把路径push到pics数据中
      const picsInfo = { pic: response.data.tem_path };
      this.addForm.pcis.push(this.pcisInfo);
    },
    // 添加商品
    add(){
      this.$refs.addFormRefs.validate(async valid =>{
        if(!valid){
          return this.$message.error('请选择必要的参数！')
        }
        // 预验证成功
        // 深拷贝
        const form = _.cloneDeep(this.addForm)
        form.goods_cat = form.goods_cat.join(',')
        // 处理动态属性
        this.manyTabData.forEach(item => {
          const newInfo = {
            attr_id : item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        });

        // 处理静态属性
        this.onlyTabData.forEach(item => {
          const newInfo = {
            attr_id : item.attr_id,
            attr_value: item.attr_vals
          }
          this.addForm.attrs.push(newInfo)
        });

        form.attrs = this.addForm.attrs
        // 发起网络请求
        const {data: res} = await this.$http.post('goods',form)

        if(res.meta.status !==  201){
          return this.$message.error('提交数据失败')
        }

        this.$message.success('提交成功！')
        this.$router.push('/goods')
      })
    }
  },
  created() {
    // 获取商品分类数据
    this.getCateList();
  },
  // 计算属性
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2];
      }

      return null;
    }
  }
};
</script>

<style>
.marginTop {
  margin-top: 1%;
}

.el-step__title {
  font-size: 14px;
}

.checkbox {
  margin: 0 10 0 0 !important;
}

.ql-editor{
  min-height: 300px;
}
</style>